package com.ivifi.shirodemo.realm;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ivifi.shirodemo.dto.Role;
import com.ivifi.shirodemo.dto.User;
import com.ivifi.shirodemo.Server.RoleService;
import com.ivifi.shirodemo.Server.UserSer;

public class UserRealm extends AuthorizingRealm {
	
	@Autowired
	UserSer userService;
	
	@Autowired
	RoleService roleService;
     
    @Autowired
	User user;
    
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		System.out.println("进行权限验证");
		String userName = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		/** 添加角色权限 **/
		Role role=roleService.findOne(null);
		authorizationInfo.addRole(role.getRoleStr());
		authorizationInfo.addStringPermission("admin:create");
		authorizationInfo.addStringPermission("admin:scan");
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String userName = (String) token.getPrincipal();
		String password = "";
		user.setUserName(userName);
		System.out.println("user:"+user);
	 	user=userService.selectUser(user);
		System.out.println("进行身份验证：" + user.getUserName()+" password:"+user.getUserPassword());
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				userName, user.getUserPassword(), getName());
		return authenticationInfo;
	}

}
